<?php

declare(strict_types=1);

namespace App\Controller\Backend;

use App\Logic\AdminLogic;
use Exception;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\AutoController;
use Psr\Http\Message\ResponseInterface;

#[AutoController(prefix: '/admin', server: 'backend')]
class AdminController extends AbstractController
{
    /**
     * 管理员列表
     * @return ResponseInterface
     */
    public function lists(): ResponseInterface
    {
        $input = $this->request->all();
        $data = AdminLogic::lists($input);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 添加管理员
     * @return ResponseInterface
     */
    public function add(): ResponseInterface
    {
        $input = $this->request->all();
        try {
            if (empty($input['username']) || strlen($input['username']) < 6 || strlen($input['username']) > 20) {
                return $this->apiReturn(400, '用户名应该保持6~20位');
            }
            if (empty($input['nickname'])) {
                return $this->apiReturn(400, '昵称不能为空');
            }
            if (strlen($input['password']) < 6 || strlen($input['password']) > 20) {
                return $this->apiReturn(400, '密码应保持6~20位');
            }
            AdminLogic::add($input);
            return $this->apiReturn(200, '添加成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 删除管理员
     * @return ResponseInterface
     */
    public function delete(): ResponseInterface
    {
        $userId = $this->request->input('userid', 0);
        if (!$userId) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            AdminLogic::delete($userId);
            return $this->apiReturn(200, '删除成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 修改管理员信息
     * @return ResponseInterface
     */
    public function edit(): ResponseInterface
    {
        $input = $this->request->all();
        $userId = $input['userid'] ?? 0;
        if (!$userId) {
            return $this->apiReturn(400, '参数错误');
        }
        try {
            AdminLogic::edit($userId, $input);
            return $this->apiReturn(200, '修改成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage().':'.$e->getFile().':'.$e->getLine());
        }
    }

    /**
     * 修改当前管理员密码
     * @return ResponseInterface
     */
    public function password(): ResponseInterface
    {
        $password = $this->request->input('password');
        if (empty($password)) {
            return $this->apiReturn(400, '请输入密码');
        }
        if (strlen($password) < 6 || strlen($password) > 20) {
            return $this->apiReturn(400, '请确保密码长度在6~20位');
        }
        AdminLogic::password($password);
        return $this->apiReturn(200, '修改成功，请重新登录!');
    }
}